<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
class Issue extends Controller
{
    protected $middleware = ['Auth'];

    public function approval(Request $request){
        $post = input('post.');
        if(!isInt($post['num']))
            return json(["code"=>-1,"msg"=>"请输入正确的数量"]);
        if(!$product = Db::name('product')->where(['id'=>$post['id'],'status'=>1])->find())
            return json(["code"=>-1,"msg"=>"产品不存在"]);
        $product['num'] = $post['num'];
        $product['product_id'] = $product['id'];
        $product['user_id'] = $request->userInfo['id'];
        $product['user_type'] = $request->userInfo['type'];
        $product['user_nickname'] = $request->userInfo['nickname'];
        unset($product['status']);
        unset($product['id']);
        unset($product['approval_refuse_msg']);
        unset($product['gj_num']);
        unset($product['hx_num']);
        unset($product['test_num']);
        if(!Db::name('issue')->insert($product))
            return json(["code"=>-1,"msg"=>"申请失败"]);

        $this->approvalNumInc($post['id'],$request->userInfo['type'],$post['num']);
        return json(["code"=>200,"msg"=>"申请成功"]);
    }

    private function approvalNumInc($id,$type,$num = 1){
        if($type == 1)
            Db::name('product')->where(['id'=>$id])->setInc('gj_num',$num);
        if($type == 2)
            Db::name('product')->where(['id'=>$id])->setInc('hx_num',$num);
        if($type == 3)
            Db::name('product')->where(['id'=>$id])->setInc('test_num',$num);
    }

    public function cancel(){
        $post = input('post.');
        if(Db::name('issue')->where(['id'=>$post['id'],'status'=>0])->update(['status'=>2]))
            return json(['code'=>200,'msg'=>'取消成功']);
        return json(['code'=>-1,'msg'=>'取消失败']);
    }

    public function handle(){
        $post = input('post.');
        if(Db::name('issue')->where(['id'=>$post['id'],'status'=>0])->update(['status'=>1]))
            return json(['code'=>200,'msg'=>'处理成功']);
        return json(['code'=>-1,'msg'=>'处理失败']);
    }
}